<template>
  <div class="front-rooms-page">
    <!-- 顶部导航 -->
    <CommonHeader />

    <!-- 主要内容区 -->
    <div class="main-content">
      <!-- 搜索框上方的快捷入口 -->
      <div class="quick-entries">
        <div class="entry-card" @click="handleQuickEntry('popular')">
          <i class="el-icon-star-on"></i>
          <span>热门推荐</span>
        </div>
        <div class="entry-card" @click="handleQuickEntry('near')">
          <i class="el-icon-location"></i>
          <span>附近自习室</span>
        </div>
        <div class="entry-card" @click="handleQuickEntry('discount')">
          <i class="el-icon-price-tag"></i>
          <span>优惠活动</span>
        </div>
        <div class="entry-card" @click="handleQuickEntry('guide')">
          <i class="el-icon-guide"></i>
          <span>新手指南</span>
        </div>
      </div>

      <!-- 搜索区域 -->
      <div class="search-section">
        <div class="search-bar">
          <input 
            type="text" 
            v-model="searchQuery" 
            placeholder="搜索自习室名称或位置..."
            @input="handleSearch"
          >
          <i class="el-icon-search"></i>
        </div>
        <!-- 搜索框下方的快捷标签 -->
        <div class="quick-tags">
          <span v-for="tag in quickTags" :key="tag" @click="handleQuickSearch(tag)">
            {{ tag }}
          </span>
        </div>
      </div>

      <!-- 右侧悬浮工具栏 -->
      <div class="floating-toolbar">
        <div class="tool-item" @click="scrollToTop" v-show="showBackTop">
          <i class="el-icon-top"></i>
          <span>返回顶部</span>
        </div>
        <div class="tool-item" @click="handleScan">
          <i class="el-icon-camera"></i>
          <span>扫码入座</span>
        </div>
        <div class="tool-item" @click="showFeedback">
          <i class="el-icon-message"></i>
          <span>意见反馈</span>
        </div>
        <div class="tool-item" @click="showHelp">
          <i class="el-icon-question"></i>
          <span>帮助中心</span>
        </div>
      </div>

     
      <!-- 筛选区域 -->
      <div class="filter-section">
        <div class="filter-row">
          <div class="filter-label">类型</div>
          <div class="filter-options">
            <div 
              v-for="type in roomTypes" 
              :key="type.value"
              class="filter-option"
              :class="{ active: selectedType === type.value }"
              @click="selectedType = type.value"
            >
              <i :class="type.icon"></i>
              {{ type.label }}
            </div>
          </div>
        </div>
        <div class="filter-row">
          <div class="filter-label">设施</div>
          <div class="filter-options">
            <div 
              v-for="facility in facilities" 
              :key="facility.value"
              class="filter-option"
              :class="{ active: selectedFacilities.includes(facility.value) }"
              @click="toggleFacility(facility.value)"
            >
              <i :class="facility.icon"></i>
              {{ facility.label }}
            </div>
          </div>
        </div>
      </div>

      <!-- 添加排序控制区域 -->
      <div class="sort-section">
        <div class="sort-options">
          <span 
            v-for="option in sortOptions" 
            :key="option.value"
            class="sort-item"
            :class="{ active: currentSort === option.value }"
            @click="currentSort = option.value"
          >
            {{ option.label }}
            <i class="el-icon-d-caret"></i>
          </span>
        </div>
      </div>

      <!-- 房间列表 -->
      <div class="rooms-grid">
        <div 
          v-for="room in filteredRooms" 
          :key="room.id"
          class="room-card"
          @click="goToDetail(room.id)"
        >
          <div class="room-image" :style="{ backgroundImage: `url(${room.image || defaultImage})` }">
            <div class="room-status" :class="getStatusClass(room.status)">
              {{ getStatusText(room.status) }}
            </div>
          </div>
          <div class="room-info">
            <h3>{{ room.roomName }}</h3>
            <div class="room-meta">
              <span><i class="el-icon-location"></i>{{ room.location }}</span>
              <span><i class="el-icon-user"></i>{{ room.availableSeats }}/{{ room.totalSeats }}</span>
            </div>
            <div class="room-features">
              <span v-for="(feature, index) in room.equipment" :key="index">
                <i :class="getFeatureIcon(feature)"></i>
                {{ feature }}
              </span>
            </div>
            <div class="room-description">{{ room.description }}</div>
          </div>
          <div class="room-footer">
            <div class="room-rating">
              <i class="el-icon-star-on"></i>
              <span>{{ room.rating || '4.5' }}</span>
            </div>
            <button class="book-btn" @click.stop="handleBook(room)">
              立即预约
            </button>
          </div>
        </div>
      </div>

      <!-- 加载更多 -->
      <div class="load-more" v-if="hasMore" @click="loadMore">
        <span v-if="!loading">加载更多</span>
        <span v-else>加载中...</span>
      </div>
    </div>
  </div>
</template>
  
<script>
import CommonHeader from '@/components/Header.vue'
import request from '@/utils/request'
import _ from 'lodash'
  
export default {
  name: 'RoomsList',
  components: {
    CommonHeader
  },
  data() {
    // 使用一个简单的渐变背景作为默认图片
    const svg = `
      <svg xmlns="http://www.w3.org/2000/svg" width="800" height="400">
        <defs>
          <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" style="stop-color:#67C23A;stop-opacity:1" />
            <stop offset="100%" style="stop-color:#409EFF;stop-opacity:1" />
          </linearGradient>
        </defs>
        <rect width="800" height="400" fill="url(#grad)"/>
        <text x="400" y="180" font-family="Arial" font-size="48" fill="white" text-anchor="middle" font-weight="bold">YOYO自习室</text>
        <text x="400" y="240" font-family="Arial" font-size="24" fill="white" text-anchor="middle">安静 · 舒适 · 高效</text>
      </svg>
    `;

    const defaultImage = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg.trim())));

    return {
      searchQuery: '',
      selectedType: 'all',
      selectedFacilities: [],
      currentSort: 'recommend',
      rooms: [],
      loading: false,
      hasMore: true,
      page: 1,
      roomTypes: [
        { label: '全部', value: 'all', icon: 'el-icon-house' }
      ],
      facilities: [],
      defaultImage,
      sortOptions: [
        { label: '推荐排序', value: 'recommend' },
        { label: '空位优先', value: 'seats' },
        { label: '评分优先', value: 'rating' }
      ],
      stats: {
        totalRooms: 0,
        availableSeats: 0,
        usageRate: 0
      },
      quickTags: ['靠窗位置', '安静区域', '研讨室', '电脑区', '24小时'],
      showBackTop: false
    }
  },
  computed: {
    filteredRooms() {
      if (!this.rooms) return []
      return this.rooms
    }
  },
  created() {
    this.getRooms()
    this.getCategories()
    this.getFacilities()
    // this.getStats()
  },
  methods: {
    async getRooms() {
      this.loading = true
      try {
        console.log('请求参数:', {
          page: this.page,
          size: 12,
          type: this.selectedType === 'all' ? undefined : this.selectedType,
          facilities: this.selectedFacilities?.join(',') || '',
          sort: this.currentSort
        })

        const res = await request({
          url: '/api/study/studyroom/filter',
          method: 'get',
          params: {
            page: this.page,
            size: 12,
            type: this.selectedType === 'all' ? undefined : this.selectedType,
            facilities: this.selectedFacilities?.join(',') || '',
            sort: this.currentSort
          }
        })
        console.log('获取到的房间数据:', res)

        if (res.code === 200) {
          const { records, total } = res.data
          const formattedRooms = records.map(room => ({
            id: room.id,
            roomName: room.roomName,
            totalSeats: room.totalSeats,
            availableSeats: room.availableSeats,
            location: room.location,
            status: room.status,
            description: room.description,
            type: room.type,
            typeName: room.typeName,
            equipment: room.equipment ? room.equipment.split(',') : [],
            rating: room.averageRating,
            image: room.img || this.defaultImage
          }))

          if (this.page === 1) {
            this.$set(this, 'rooms', formattedRooms)
          } else {
            this.$set(this, 'rooms', [...this.rooms, ...formattedRooms])
          }
          this.hasMore = this.rooms.length < total
        }
      } catch (error) {
        console.error('获取自习室列表失败:', error)
        this.$message.error('获取自习室列表失败，请稍后重试')
      }
      this.loading = false
    },
    handleSearch: _.debounce(function() {
      this.page = 1
      this.getRooms()
    }, 300),
    loadMore() {
      if (!this.loading && this.hasMore) {
        this.page++
        this.getRooms()
      }
    },
    goToDetail(id) {
      this.$router.push(`/room/detail/${id}`)
    },
    handleBook(room) {
      if (room.status !== 1) {
        this.$message.warning('该自习室当前不可预约')
        return
      }
      this.$router.push(`/room/detail/${room.id}`)
    },
    getStatusClass(status) {
      const classMap = {
        0: 'closed',
        1: 'open',
        2: 'maintain'
      }
      return classMap[status] || 'closed'
    },
    getStatusText(status) {
      const statusMap = {
        0: '暂停使用',
        1: '营业中',
        2: '维护中'
      }
      return statusMap[status] || '未知状态'
    },
    getFeatureIcon(feature) {
      const facility = this.facilities.find(f => f.label === feature)
      return facility ? facility.icon : 'el-icon-setting'
    },
    toggleFacility(value) {
      if (this.selectedFacilities.includes(value)) {
        this.selectedFacilities = this.selectedFacilities.filter(item => item !== value)
      } else {
        this.selectedFacilities.push(value)
      }
      this.handleFilterChange()
    },
    handleFilterChange() {
      this.page = 1
      this.getRooms()
    },
    handleSortChange() {
      this.page = 1
      this.getRooms()
    },
    getStatusType(status) {
      const typeMap = {
        0: 'danger',  // 暂停使用
        1: 'success', // 营业中
        2: 'warning'  // 维护中
      }
      return typeMap[status] || 'info'
    },
    async getCategories() {
      try {
        const res = await request({
          url: '/api/study/studyroom/categories',
          method: 'get'
        })
        console.log('获取到的类型数据:', res)

        if (res && Array.isArray(res)) {
          // 扩展图标映射
          const iconMap = {
            'home': 'el-icon-house',
            'personal': 'el-icon-reading',
            'meeting': 'el-icon-office-building',
            'computer': 'el-icon-monitor',
            'relax': 'el-icon-coffee-cup',
            // 新增图标映射
            'multimedia': 'el-icon-video-camera',
            'quiet': 'el-icon-turn-off-microphone',
            'book': 'el-icon-notebook-2',
            'maker': 'el-icon-magic-stick',
            'team': 'el-icon-user-solid',
            'exam': 'el-icon-edit-outline',
            'casual': 'el-icon-coffee',
            'outdoor': 'el-icon-sunny',
            '24h': 'el-icon-time',
            'focus': 'el-icon-aim'
          }
          
          // 保留"全部"选项
          const allOption = { 
            label: '全部', 
            value: 'all', 
            icon: 'el-icon-house' 
          }
          
          // 过滤和映射类型数据
          const categories = res
            .filter(item => item.isEnabled && !item.isDeleted)
            .map(item => ({
              label: item.name,
              value: item.id,
              icon: iconMap[item.icon] || 'el-icon-setting',
              description: item.description
            }))
          
          console.log('处理后的类型数据:', [allOption, ...categories])
          
          this.roomTypes = [allOption, ...categories]
          this.$forceUpdate()
        }
      } catch (error) {
        console.error('获取自习室类型失败:', error)
        this.$message.error('获取自习室类型失败，请稍后重试')
      }
    },
    async getFacilities() {
      try {
        const res = await request({
          url: '/api/study/studyroom/facilities',
          method: 'get'
        })
        console.log('获取到的设施数据:', res)

        if (res && Array.isArray(res)) {
          // 过滤和处理设施数据
          this.facilities = res
            .filter(item => item.isEnabled && !item.isDeleted)
            .map(item => ({
              label: item.name,
              value: item.code,
              icon: `el-icon-${item.icon}`,
              description: item.description
            }))
          console.log('处理后的设施数据:', this.facilities)
        }
      } catch (error) {
        console.error('获取设施列表失败:', error)
        this.$message.error('获取设施列表失败，请稍后重试')
      }
    },
    async getStats() {
      try {
        const res = await request({
          url: '/api/study/studyroom/stats',
          method: 'get'
        })
        if (res.code === 200) {
          this.stats = res.data
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    handleQuickEntry(type) {
      switch(type) {
        case 'popular':
          this.currentSort = 'rating'
          break
        case 'near':
          // 获取用户位置并筛选附近自习室
          break
        case 'discount':
          this.$message('敬请期待优惠活动')
          break
        case 'guide':
          this.$message('即将跳转到新手指南')
          break
      }
    },
    handleQuickSearch(tag) {
      this.searchQuery = tag
      this.handleSearch()
    },
    handleScan() {
      this.$message('请打开手机扫一扫')
    },
    showFeedback() {
      this.$message('感谢您的反馈')
    },
    showHelp() {
      this.$message('正在跳转到帮助中心')
    },
    scrollToTop() {
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
  },
  watch: {
    selectedType: {
      handler(newVal) {
        console.log('选中的类型变化:', newVal)
        this.handleFilterChange()
      },
      immediate: true
    },
    currentSort() {
      this.handleSortChange()
    }
  },
  mounted() {
    // 确保在 DOM 更新后再获取类型数据
    this.$nextTick(() => {
      this.getCategories()
    })
    // 监听滚动显示返回顶部按钮
    window.addEventListener('scroll', () => {
      this.showBackTop = window.pageYOffset > 300
    })
  }
}
</script>
  
<style scoped>
.front-rooms-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.filter-row {
  display: flex;
  padding: 15px 0;
  border-bottom: 1px solid #ebeef5;
}

.filter-row:last-child {
  border-bottom: none;
}

.filter-label {
  width: 80px;
  color: #606266;
  font-size: 14px;
  padding-top: 8px;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.filter-option {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
  background: #f5f7fa;
  color: #606266;
}

.filter-option:hover {
  background: #ecf5ff;
  color: #409EFF;
}

.filter-option.active {
  background: #409EFF;
  color: white;
}

.rooms-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}
  
.search-section {
  margin-bottom: 30px;
}
  
.search-bar {
  position: relative;
  margin-bottom: 20px;
}
  
.search-bar input {
  width: 100%;
  padding: 15px 20px;
  padding-left: 50px;
  border: none;
  border-radius: 12px;
  background: white;
  font-size: 16px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
  
.search-bar i {
  position: absolute;
  left: 20px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  font-size: 20px;
}
  
.filters {
  display: flex;
  gap: 15px;
  overflow-x: auto;
  padding-bottom: 10px;
}
  
.filter-item {
  padding: 8px 20px;
  border-radius: 20px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
  
.filter-item.active {
  background: #409EFF;
  color: white;
}
  
.rooms-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}
  
.room-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}
  
.room-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}
  
.room-image {
  height: 180px;
  background-size: cover;
  background-position: center;
  position: relative;
}
  
.room-status {
  position: absolute;
  top: 15px;
  right: 15px;
  padding: 6px 12px;
  border-radius: 20px;
  color: white;
  font-size: 12px;
  backdrop-filter: blur(10px);
}
  
.room-status.open {
  background: rgba(103, 194, 58, 0.9);
}
  
.room-status.closed {
  background: rgba(245, 108, 108, 0.9);
}
  
.room-status.maintain {
  background: rgba(230, 162, 60, 0.9);
}
  
.room-info {
  padding: 20px;
}
  
.room-info h3 {
  margin: 0 0 10px;
  font-size: 18px;
  color: #303133;
}
  
.room-meta {
  display: flex;
  gap: 15px;
  color: #606266;
  font-size: 14px;
  margin-bottom: 15px;
}
  
.room-meta span {
  display: flex;
  align-items: center;
  gap: 5px;
}
  
.room-features {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}
  
.room-features span {
  padding: 4px 8px;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
  color: #606266;
  display: flex;
  align-items: center;
  gap: 4px;
}
  
.room-description {
  color: #909399;
  font-size: 14px;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
  
.room-footer {
  padding: 15px 20px;
  border-top: 1px solid #f0f2f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
  
.room-rating {
  color: #F7BA2A;
  display: flex;
  align-items: center;
  gap: 5px;
}
  
.book-btn {
  padding: 8px 20px;
  border: none;
  border-radius: 20px;
  background: #409EFF;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}
  
.book-btn:hover {
  background: #66b1ff;
  transform: translateY(-2px);
}
  
.load-more {
  text-align: center;
  margin-top: 30px;
  padding: 15px;
  color: #409EFF;
  cursor: pointer;
}
  
@media (max-width: 768px) {
  .rooms-page {
    padding: 10px;
  }
    
  .rooms-grid {
    grid-template-columns: 1fr;
  }
    
  .room-image {
    height: 150px;
  }
}

.room-card {
  margin-bottom: 20px;
}

.room-image {
  height: 200px;
  background-size: cover;
  background-position: center;
  position: relative;
}

.room-info {
  padding: 20px;
}

.room-meta {
  margin: 10px 0;
  display: flex;
  gap: 15px;
}

.room-features {
  margin: 10px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.room-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-status {
  position: absolute;
  top: 10px;
  right: 10px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  margin-bottom: 15px;
}

.filter-label {
  margin-bottom: 10px;
  font-weight: bold;
}

.search-section {
  margin-bottom: 20px;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

/* 添加排序区域样式 */
.sort-section {
  background: white;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sort-options {
  display: flex;
  gap: 20px;
}

.sort-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
  padding: 6px 12px;
  border-radius: 4px;
}

.sort-item:hover {
  color: #409EFF;
  background: #ecf5ff;
}

.sort-item.active {
  color: #409EFF;
  font-weight: 500;
}

.sort-item i {
  font-size: 12px;
  transition: transform 0.3s;
}

.sort-item.active i {
  transform: rotate(180deg);
}

@media (max-width: 768px) {
  .sort-options {
    gap: 10px;
  }

  .sort-item {
    padding: 4px 8px;
    font-size: 14px;
  }
}

.stats-section {
  max-width: 1200px;
  margin: 20px auto;
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 0 20px;
}

.stat-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.stat-card i {
  font-size: 40px;
  color: #409EFF;
  background: #ecf5ff;
  padding: 15px;
  border-radius: 10px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.quick-entries {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 30px;
}

.entry-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.entry-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}

.entry-card i {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 10px;
}

.entry-card span {
  display: block;
  color: #606266;
  font-size: 14px;
}

.quick-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.quick-tags span {
  padding: 4px 12px;
  background: #f5f7fa;
  border-radius: 16px;
  font-size: 12px;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-tags span:hover {
  background: #ecf5ff;
  color: #409EFF;
}

.floating-toolbar {
  position: fixed;
  right: 30px;
  bottom: 100px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  z-index: 99;
}

.tool-item {
  width: 50px;
  height: 50px;
  background: white;
  border-radius: 25px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  transition: all 0.3s;
}

.tool-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(0,0,0,0.15);
}

.tool-item i {
  font-size: 20px;
  color: #409EFF;
}

.tool-item span {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  display: none;
}

.tool-item:hover span {
  display: block;
}

@media (max-width: 768px) {
  .quick-entries {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .floating-toolbar {
    right: 15px;
    bottom: 70px;
  }
}
</style> 